﻿Imports vb = Microsoft.VisualBasic
Imports DevComponents.DotNetBar
Imports DevComponents.DotNetBar.Controls

Module mdQuanLyBanHang
    Enum ActionType
        AddRecord = 0
        EditRecord = 1
        ViewRecord = 2
    End Enum
    Enum Department
        Sales = 0
        Financial = 1
    End Enum
    Enum CurrencyType
        USD = 0
        VND = 1
    End Enum
    Enum DateTimeFormatType
        DMY
        MDY
        YMD
        YDM
    End Enum
    'Public sEmailSupport As String
    Public objUser As UserDTO
    Public objErrorLog As ErrorDAO
    Public objConnectionDAO As ConnectionDAO
    Public eDepartment As Department
    Public RateOfExchange As Double
    Public eCurrencyType As CurrencyType
    Public eDateTimeFormatType As DateTimeFormatType
    'Dim wQLBH As frmQuanlybanhangu

    Function ChangeUnicodeToAnscii(ByVal needchangestring As String) As String

        Dim source_1 As String = "ăâđêôơưàảãạáằẳẵặắầẩẫậấèẻẽẹéềểễệếìỉĩịíòỏõọóồổỗộốờởỡợớùủũụúừửữựứỳỷỹỵýĂÂĐÊÔƠƯÀẢÃẠÁẰẲẴẶẮẦẨẪẬẤÈẺẼẸÉỀỂỄỆẾÌỈĨỊÍÒỎÕỌÓỒỔỖỘỐỜỞỠỢỚÙỦŨỤÚỪỬỮỰỨỲỶỸỴÝ"
        Dim source_2 As String = "aadeoouaaaaaaaaaaaaaaaeeeeeeeeeeiiiiiooooooooooooooouuuuuuuuuuyyyyyAADEOOUAAAAAAAAAAAAAAAEEEEEEEEEEIIIIIOOOOOOOOOOOOOOOUUUUUUUUUUYYYYY"
        Dim changedString As String = ""
        For Each c As Char In needchangestring
            Dim flag = False
            For Each c2 As Char In source_1
                If String.Equals(c, c2) = True Then
                    changedString += source_2.Chars(source_1.IndexOf(c))
                    flag = True
                    'changedString(changedString.IndexOf(c)) = source_2.Chars(source_1.IndexOf(c2))
                End If
            Next
            If flag = False Then
                changedString += c
                flag = False
            End If

        Next
        Return changedString.ToLower()
    End Function

    Public Function SearchbyComboboxValue(ByVal _grid As DataGridViewX, _
                                          ByVal _filterBy As String, _
                                          ByVal _filterType As String, _
                                          ByVal _searchtext As String, _
                                          ByVal _datasource As DataTable) As DataTable
        Dim columnIndex As Integer
        For Each ele As DataGridViewColumn In _grid.Columns
            If ele.HeaderText = _filterBy Then
                columnIndex = ele.Index
                Exit For
            End If
        Next

        'columnIndex += 1

        Dim dt1, dt2 As New DataTable()
        dt1 = _datasource

        For Each ecol As DataColumn In _datasource.Columns
            Dim ncol As New DataColumn(ecol.ColumnName)
            dt2.Columns.Add(ncol)
        Next


        For Each row As DataRow In dt1.Rows
            'If row.Item(columnIndex).Contains(_searchtext) = True Then
            '    'dt.Rows.Add(_grid.Rows(index))
            '    dt2.Rows.Add(row)
            'End If
            Try
                If _filterType = "Date" Then

                Else
                    If row.Item(columnIndex).Contains(_searchtext) Then
                        Dim nrow As DataRow
                        nrow = dt2.NewRow()
                        For index = 0 To dt1.Columns.Count - 1
                            nrow(index) = row(index)
                        Next
                        dt2.Rows.Add(nrow)

                    ElseIf ChangeUnicodeToAnscii(row.Item(columnIndex)).Contains(ChangeUnicodeToAnscii(_searchtext)) Then
                        Dim nrow As DataRow
                        nrow = dt2.NewRow()
                        For index = 0 To dt1.Columns.Count - 1
                            nrow(index) = row(index)
                        Next
                        dt2.Rows.Add(nrow)

                    End If
                End If


            Catch ex As Exception

            End Try

        Next


        'For Each _row As DataGridViewRow In _grid.Rows
        '    If _row.Cells(columnIndex).Value.ToString().Contains(_searchtext) = True Then
        '        dt.Rows.Add(_row)
        '    End If
        'Next

        Return dt2

    End Function

    Sub InitQuanLyBanHang()
        Try
            SetDate()
            objUser = New UserDTO()
            objConnectionDAO = New ConnectionDAO()
            objErrorLog = New ErrorDAO()
        Catch ex As Exception
            MessageBox.Show("Không tìm thấy máy chủ để kết nối, Vui lòng thử lại .", "Lỗi truy cập", MessageBoxButtons.OKCancel)
        End Try

    End Sub

    Public Sub SetDate()
        Dim sShortDatePattern As String = Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern.ToUpper
        Dim sFormat As String()
        sFormat = sShortDatePattern.Split(Globalization.CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator)

        If sFormat(0).StartsWith("D") And sFormat(1).StartsWith("M") And sFormat(2).StartsWith("Y") Then
            eDateTimeFormatType = DateTimeFormatType.DMY
        ElseIf sFormat(0).StartsWith("M") And sFormat(1).StartsWith("D") And sFormat(2).StartsWith("Y") Then
            eDateTimeFormatType = DateTimeFormatType.MDY
        ElseIf sFormat(0).StartsWith("Y") And sFormat(1).StartsWith("D") And sFormat(2).StartsWith("M") Then
            eDateTimeFormatType = DateTimeFormatType.YDM
        ElseIf sFormat(0).StartsWith("Y") And sFormat(1).StartsWith("M") And sFormat(2).StartsWith("D") Then
            eDateTimeFormatType = DateTimeFormatType.YMD
        End If
    End Sub

    Private Function NumToText(ByVal argNumber As String) As String
        Dim so As String() = {"không", "một", "hai", "ba", "bốn", "năm", "sáu", "bảy", "tám", "chín"}
        Dim hang As String() = {"", "nghìn", "triệu", "tỉ"}

        Dim i, j, donvi, chuc, tram As Integer
        Dim str As String
        str = ""
        i = Len(argNumber)
        For j = 0 To i - 1
            If vb.Left(argNumber, 1) = "0" Then
                argNumber = vb.Right(argNumber, i - j)
            End If
        Next j
        If argNumber = "0" Then
            NumToText = so(0)
            Exit Function
        End If
        i = Len(argNumber)
        If i = 0 Then
            str = ""
        Else
            j = 0
            Do While i > 0
                donvi = Int(Mid(argNumber, i, 1))
                i = i - 1
                If i > 0 Then
                    chuc = Int(Mid(argNumber, i, 1))
                Else
                    chuc = -1
                End If
                i = i - 1
                If i > 0 Then
                    tram = Int(Mid(argNumber, i, 1))
                Else
                    tram = -1
                End If
                i = i - 1
                If donvi > 0 Or chuc > 0 Or tram > 0 Or j = 3 Then
                    str = hang(j) & " " & str
                End If
                j = j + 1
                If j > 3 Then
                    j = 1
                End If
                If donvi = 1 And chuc > 1 Then
                    str = "mốt" & " " & str
                Else
                    If donvi = 5 And chuc > 0 Then
                        str = "lăm" & " " & str
                    ElseIf donvi > 0 Then
                        str = so(donvi) & " " & str
                    End If
                End If
                If chuc < 0 Then
                    Exit Do
                Else
                    If chuc = 0 And donvi > 0 Then
                        str = "lẻ" & " " & str
                    ElseIf chuc = 1 Then
                        str = "mười" & " " & str
                    ElseIf chuc > 1 Then
                        str = so(chuc) & " " & "mươi" & " " & str
                    End If
                End If
                If tram < 0 Then
                    Exit Do
                Else
                    If tram > 0 Or chuc > 0 Or donvi > 0 Then
                        str = so(tram) & " " & "trăm" & " " & str
                    End If
                End If
            Loop
        End If
        str = Trim(str)
        str = UCase(vb.Left(str, 1)) & vb.Right(str, Len(str) - 1)
        NumToText = str
    End Function

    Public Function NumToText(ByVal argNumber As String, ByVal argOddNumSymbol As String) As String
        Dim sFirst As String
        Dim sLast As String
        If argNumber.IndexOf(argOddNumSymbol) <> -1 Then
            sFirst = argNumber.Substring(0, argNumber.IndexOf(argOddNumSymbol))
            sLast = argNumber.Substring(argNumber.IndexOf(argOddNumSymbol) + 1, argNumber.Length - (argNumber.IndexOf(argOddNumSymbol) + 1))
            NumToText = NumToText(sFirst)
            If Integer.Parse(Trim(sLast)) <> 0 Then
                NumToText += " phẩy " & NumToText(sLast).ToLower
            End If
        Else
            NumToText = NumToText(argNumber)
        End If
    End Function

    Public Function SearchUserGrid(ByVal SearchFor As String, ByVal FilteredBy As String, ByVal Tag As String, ByVal myTable As DataTable) As DataView
        Dim myDataView As DataView
        If Tag = "String" And IsNumeric(SearchFor) = False Then
            SearchFor = "*" & SearchFor & "*"
        End If
        Try
            If Tag = "Date" Then
                Dim arrDate As String()
                Dim strDK As String = Nothing

                Select Case True
                    Case Microsoft.VisualBasic.Left(SearchFor, 2) = "<>"
                        strDK = "<>"
                        SearchFor = SearchFor.Replace("<>", Nothing)
                    Case Microsoft.VisualBasic.Left(SearchFor, 2) = ">="
                        strDK = ">="
                        SearchFor = SearchFor.Replace(">=", Nothing)
                    Case Microsoft.VisualBasic.Left(SearchFor, 2) = "<="
                        strDK = "<="
                        SearchFor = SearchFor.Replace("<=", Nothing)
                    Case Microsoft.VisualBasic.Left(SearchFor, 1) = ">"
                        strDK = ">"
                        SearchFor = SearchFor.Replace(">", Nothing)
                    Case Microsoft.VisualBasic.Left(SearchFor, 1) = "<"
                        strDK = "<"
                        SearchFor = SearchFor.Replace("<", Nothing)
                End Select

                arrDate = SearchFor.Split("/")
                If arrDate.Length > 0 Then
                    SearchFor = strDK & arrDate(1) & "/" & arrDate(0) & "/" & arrDate(2)
                Else
                    MsgBox("Dữ liệu nhập không đúng định dạng (ngày/tháng/năm)", MsgBoxStyle.Critical, "Lỗi")
                    'Exit Function
                End If
            End If
            myDataView = New DataView(myTable)
            Select Case True
                Case Microsoft.VisualBasic.Left(SearchFor, 2) = "<>"
                    If InStr(SearchFor, "*", CompareMethod.Text) = 0 Then
                        myDataView.RowFilter = FilteredBy & " <> '" & Mid(SearchFor, 3, Len(SearchFor) - 2) & "'"
                    Else
                        myDataView.RowFilter = FilteredBy & " not like '" & Mid(SearchFor, 3, Len(SearchFor) - 2) & "'"
                    End If

                Case Microsoft.VisualBasic.Left(SearchFor, 2) = ">="
                    myDataView.RowFilter = FilteredBy & " >= '" & Mid(SearchFor, 3, Len(SearchFor) - 2) & "'"

                Case Microsoft.VisualBasic.Left(SearchFor, 2) = "<="
                    myDataView.RowFilter = FilteredBy & " <= '" & Mid(SearchFor, 3, Len(SearchFor) - 2) & "'"

                Case Microsoft.VisualBasic.Left(SearchFor, 1) = ">"
                    myDataView.RowFilter = FilteredBy & " > '" & Mid(SearchFor, 2, Len(SearchFor) - 1) & "'"

                Case Microsoft.VisualBasic.Left(SearchFor, 1) = "<"
                    myDataView.RowFilter = FilteredBy & " < '" & Mid(SearchFor, 2, Len(SearchFor) - 1) & "'"

                Case Else
                    If InStr(SearchFor, "*", CompareMethod.Text) = 0 Then
                        If Tag = "Date" Then
                            myDataView.RowFilter = FilteredBy & " >= '" & Format(CDate(SearchFor), "yyyy-MM-dd") & " 00:00:00' and " & _
                            FilteredBy & " <= '" & Format(CDate(SearchFor), "yyyy-MM-dd") & " 12:59:59'"
                        Else
                            myDataView.RowFilter = FilteredBy & " = '" & SearchFor & "'"
                        End If
                    Else
                        myDataView.RowFilter = FilteredBy & " like '" & SearchFor & "'"
                    End If
            End Select

            Return myDataView
        Catch ex As Exception
            MsgBox("Dữ liệu nhập không hợp lệ", MsgBoxStyle.Exclamation, "Chú ý")
        End Try

    End Function

    Public Function StringDecode(ByVal value As String, Optional ByVal key As String = "32") As String
        Dim dataValue As String = ""
        Dim calcHash As String = ""
        Dim storedHash As String = ""

        Dim mac3des As New System.Security.Cryptography.MACTripleDES
        Dim md5 As New System.Security.Cryptography.MD5CryptoServiceProvider
        mac3des.Key = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(key))

        Try
            dataValue = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(value.Split(Chr(0))(0)))
            storedHash = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(value.Split(Chr(0))(1)))
            calcHash = System.Text.Encoding.UTF8.GetString( _
              mac3des.ComputeHash(System.Text.Encoding.UTF8.GetBytes(dataValue)))

            If storedHash <> calcHash Then
                Throw New ArgumentException("Hash value does not match")
            End If
        Catch ex As Exception
            objErrorLog.SaveError(ex.Message, "clCommon", "StringDecode", objUser.UserFullName)
        End Try

        Return dataValue

    End Function

    Public Function StringEncode(ByVal value As String, Optional ByVal key As String = "32") As String
        Dim mac3des As New System.Security.Cryptography.MACTripleDES
        Dim md5 As New System.Security.Cryptography.MD5CryptoServiceProvider
        Try
            mac3des.Key = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(key))
            Return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(value)) & Chr(0) & _
              Convert.ToBase64String(mac3des.ComputeHash( _
              System.Text.Encoding.UTF8.GetBytes(value)))
        Catch ex As Exception
            objErrorLog.SaveError(ex.Message, "clCommon", "StringEncode", objUser.UserFullName)
            Return ""
        End Try

    End Function

    Sub Main()
        'Dim wLogon As frmLogon
        'Dim wSplash As frmSplash
        Try
            Application.EnableVisualStyles()
            Application.DoEvents()

            'wSplash = New frmSplash
            'wSplash.Show()
            'wSplash.Refresh()
            'Thread.Sleep(2000)
            'wSplash.Close()
            Dim sShortDatePattern As String = Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern.ToUpper
            Dim sFormat As String()
            sFormat = sShortDatePattern.Split(Globalization.CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator)

            If sFormat(0).StartsWith("D") And sFormat(1).StartsWith("M") And sFormat(2).StartsWith("Y") Then
                eDateTimeFormatType = DateTimeFormatType.DMY
            ElseIf sFormat(0).StartsWith("M") And sFormat(1).StartsWith("D") And sFormat(2).StartsWith("Y") Then
                eDateTimeFormatType = DateTimeFormatType.MDY
            ElseIf sFormat(0).StartsWith("Y") And sFormat(1).StartsWith("D") And sFormat(2).StartsWith("M") Then
                eDateTimeFormatType = DateTimeFormatType.YDM
            ElseIf sFormat(0).StartsWith("Y") And sFormat(1).StartsWith("M") And sFormat(2).StartsWith("D") Then
                eDateTimeFormatType = DateTimeFormatType.YMD
            End If

            'Dim rkey As RegistryKey
            'rkey = Registry.LocalMachine.OpenSubKey("Software\Tan Dong Tien\{9B4778FA-089B-49E7-848C-DA55A460E3F3}", True)
            'If Not IsNothing(rkey) Then
            '    If IsNothing(rkey.GetValue("Phieunhap")) Then
            '        rkey.SetValue("Phieunhap", 0)
            '    End If
            '    sEmailSupport = rkey.GetValue("EmailSupport")
            'Else
            '    rkey = Registry.LocalMachine.CreateSubKey("Software\Tan Dong Tien\{9B4778FA-089B-49E7-848C-DA55A460E3F3}")
            '    rkey.SetValue("Phieunhap", 0)
            '    rkey.SetValue("EmailSupport", "vncntt2003@yahoo.com")
            'End If
            'rkey.Close()

            'wQLBH = New frmQuanlybanhang
            'wQLBH.ShowDialog()
        Catch ex As Exception
            'SendError(ex)
        End Try
    End Sub



End Module
